﻿using System;
using System.Windows.Forms;

namespace CoreReset {

    internal delegate void AddTextDelegate(string text);

    public sealed partial class DebugLogForm : Form {

        public DebugLogForm(CoreResetForm mainForm) {
            m_mainForm = mainForm;
            InitializeComponent();
        }

        public DebugLogForm(CoreResetForm mainForm, string caption) {
            m_mainForm = mainForm;
            InitializeComponent();
            Text = caption;
        }

        public void AddText(string text) {
            if (textBoxAnalysisLog.InvokeRequired) {
                var d = new AddTextDelegate(AddTextUnsafe);
                try {
                    Invoke(d, new object[] { text });
                } catch (Exception) {
                }
            } else {
                AddTextUnsafe(text);
            }
        }

        private void AddTextUnsafe(string text) {
            var lines = text.Split('\n');

            foreach (string line in lines) {
                textBoxAnalysisLog.AppendText(line + "\n");
            }
        }

        private readonly CoreResetForm m_mainForm;

        private void DebugLogForm_FormClosing(object sender, FormClosingEventArgs e) {
            if (m_mainForm != null) {
                m_mainForm.OnDebugLogFormClosing();
                if (e.CloseReason == CloseReason.UserClosing && Visible) {
                    Hide();
                    e.Cancel = true;
                }
            }
        }

        internal void ClearText() {
            textBoxAnalysisLog.Clear();
        }
    }
}